package com.common.utils;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtil {
	public static void main(String[] args) throws MessagingException {
		// 设置SMTP服务器地址、端口号等信息
		Properties properties = new Properties();
		properties.put("mail.smtp.host", "smtphz.qiye.163.com");
		properties.put("mail.smtp.port", "25");

		// 创建会话对象
		Session session = Session.getInstance(properties);
		// 获取Transport对象并连接到SMTP服务器
		Transport transport = session.getTransport("smtp");

		try {
			// 创建MimeMessage对象并指定发件人、收件人、主题、正文内容等属性
			MimeMessage message = new MimeMessage(session);

			Address fromAddress = new InternetAddress("chenjun@xyspec.com");
			Address toAddress = new InternetAddress("chenjun@xyspec.com");

			message.setFrom(fromAddress);
			message.addRecipient(Message.RecipientType.TO, toAddress);
			message.setSubject("Hello!");
			message.setText("This is a test email.");

			transport.connect();

			// 发送邮件
			transport.sendMessage(message, message.getAllRecipients());

			System.out.println("Email sent successfully!");
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		} finally {
			// 关闭与SMTP服务器的连接
			if (transport != null && transport.isConnected()) {
				transport.close();
			}
		}
	}
}
